import gulp from 'gulp'
import GulpSSH from 'gulp-ssh'
import { loadEnv } from 'vite'
import { hideBin } from 'yargs/helpers'
import yargs from 'yargs/yargs'

const argv = yargs(hideBin(process.argv)).argv

const mode = argv.mode
const env = loadEnv(mode, process.cwd(), '')

const gulpSSH = new GulpSSH({
  ignoreErrors: false,
  sshConfig: {
    host: env.VITE_HOST,
    port: env.VITE_PORT,
    username: env.VITE_USER,
    password: env.VITE_PASSWORD,
  },
})

gulp.task('clean-remote', () => {
  return gulpSSH
    .shell([
      `rm -rf ${env.VITE_REMOTE_PATH}/static ${env.VITE_REMOTE_PATH}/index.html ${env.VITE_REMOTE_PATH}/favicon.ico`,
      `mkdir -p ${env.VITE_REMOTE_PATH}`,
    ])
    .pipe(gulp.dest('logs'))
})

gulp.task('upload', () => {
  return gulp
    .src(`./dist/${mode}/**/*`, { encoding: false })
    .pipe(gulpSSH.dest(env.VITE_REMOTE_PATH))
    .on('error', (err) => {
      console.error('上传失败:', err)
      process.exit(1)
    })
    .on('end', () => console.log('上传完成!'))
})

gulp.task('deploy', gulp.series('clean-remote', 'upload'))
